package com.yunhe.policyfulfillment.authority.service.impl;

import com.yunhe.common.exception.ArgumentErrorException;
import com.yunhe.common.util.DateTimeUtils;
import com.yunhe.policyfulfillment.authority.service.FileUploadService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Date;

/**
 * @ClassName FileUploadServiceImpl
 * @Description TODO
 * @Author HeTao
 * @Date 2021/8/26 15:03
 * @Version 1.0
 **/
@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Value("${upload.imageFormat}")
    private  String  imageFormat ;

    @Value("${upload.path}")
    private  String  path ;

    @Value("${upload.uploadMaxSize}")
    private  Long  uploadMaxSize ;

    @Value("${upload.desFileSize}")
    private  Long  desFileSize ;

    @Override
    public String uploadFile(MultipartFile file) throws IOException, ArgumentErrorException {
        if(file.getSize()>uploadMaxSize){
            throw new ArgumentErrorException("该文件大小超出上传文件大小的限制，文件最大不能超过"+(uploadMaxSize/1024/1024)+"M");
        }
        //获取文件名
        String originalFilename = file.getOriginalFilename();
        String filepath = path+ DateTimeUtils.format(DateTimeUtils.PATTERN.DATE.value(),new Date())+"/"+originalFilename;
        String abbreviationPath1 = null;
        //获取最后一个.的位置
        int lastIndexOf = originalFilename.lastIndexOf(".");
        //获取文件的后缀名 .jpg
        String suffix = originalFilename.substring(lastIndexOf+1);
        File file1 = new File(filepath);
        InputStream inputStream = file.getInputStream();
        saveFile(inputStream,path+DateTimeUtils.format(DateTimeUtils.PATTERN.DATE.value(),new Date())+"/",originalFilename);

        return filepath;
    }

    @Override
    public void getFile(String filePath, HttpServletResponse response, HttpServletRequest request) throws ArgumentErrorException, IOException {
        File file = new File(filePath);
        //判断文件是否存在
        if (!file.exists()) {
            throw new ArgumentErrorException("文件不存在！");
        }
        //获取文件文名
        String fileName = file.getName();
        //设置头文件
        response.setContentType("application/octet-stream");
        response.setContentLength((int) file.length());
        // 读写操作
        InputStream bufferedInputStream = null;
        OutputStream bufferedOutputStream = null;
        try {
            bufferedInputStream = new BufferedInputStream(new FileInputStream(file));
            bufferedOutputStream = new BufferedOutputStream(response.getOutputStream());
            response.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName,"utf-8"));
            int len = 0;
            byte[] bs  = new byte[1024];
            while ((len = bufferedInputStream.read(bs)) != -1){
                bufferedOutputStream.write(bs,0,len);
            }
        } catch (IOException e) {
            throw new IOException(fileName+"文件下载失败");
        } finally {
            if(bufferedOutputStream != null) {
                try {
                    bufferedOutputStream.flush();
                    bufferedOutputStream.close();
                } catch (IOException e) {
                    throw new IOException(fileName+"文件下载失败");
                }
            }
            if(bufferedInputStream != null){
                try {
                    bufferedInputStream.close();
                }catch (IOException e){
                    throw new IOException(fileName+"文件下载失败");
                }
            }

        }
    }

    @Override
    public void deleteFile(String filePath) throws ArgumentErrorException {
        File file = new File(filePath);
        //判断文件是否存在
        if (!file.exists()) {
            throw new ArgumentErrorException("文件不存在！");
        }
        file.deleteOnExit();
        file.delete();
    }

    private void saveFile(InputStream inputStream,String filePath, String fileName) throws IOException {
        OutputStream output = null;
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            File file = new File(filePath);
            //判断文件是否存在
            if(!file.exists()){
                file.mkdirs();
            }
            File file1  = new File(filePath+fileName);
            if(!file1.exists()){
                file1.createNewFile();
            }
            output = new FileOutputStream(file1);
            bis = new BufferedInputStream(inputStream);
            bos = new BufferedOutputStream(output);
            byte[] b = new byte[1024];
            while (bis.read(b) != -1) {
                bos.write(b, 0, b.length);
            }
            //必须要添加该方法
            bos.flush();
        } catch (IOException e) {
            throw new IOException("文件上传失败");
        }finally {
            if(inputStream != null){
                inputStream.close();
            }
            if(output != null){
                output.close();
            }
            if(bis != null){
                bis.close();
            }
            if(bos != null){
                bos.close();
            }
        }
    }
}
